import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/pages/login_page.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';

class UpdatePassword extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<UpdatePassword> {
  TextEditingController _oldPwdController = new TextEditingController();
  TextEditingController _newPwdController = new TextEditingController();
  TextEditingController _repPwdController = new TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  // 修改密码
  updatePassword() {
    String oldPwd = _oldPwdController.text.trim();
    String newPwd = _newPwdController.text.trim();
    String repPwd = _repPwdController.text.trim();

    if (newPwd != repPwd) {
      Utils.showText(text: '新密码与确认密码不一致');
      return;
    }

    DioUtils.request("User/modifyPassword",
        context: context,
        method: "POST",
        params: {
          'oldpassword': oldPwd,
          'newpassword': newPwd,
          'repassword': repPwd
        }, onSuccess: (res) {
      if (res['code'] == 1) {
        Utils.showText(text: '密码修改成功，请重新登录！');
        Utils.logOut();

        Timer.periodic(Duration(milliseconds: 1600), (timer) {
          timer.cancel();
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(builder: (context) => LoginPage()),
              (route) => route == null);
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {
      // Toast.show(error);
    });
  }

  Widget _buildInputBox() {
    int index = 0;
    List<Widget> widget = [];
    List list = [
      {"title": "旧密码：", "tips": "请输入旧密码", "controller": _oldPwdController},
      {"title": "新密码：", "tips": "请输入新密码", "controller": _newPwdController},
      {"title": "确认密码：", "tips": "请再次输入密码", "controller": _repPwdController},
    ];

    for (var item in list) {
      index++;

      widget.add(Column(
        children: <Widget>[
          Container(
            height: 119.w,
            child: Row(
              children: <Widget>[
                Container(
                  width: 170.w,
                  child: Text(
                    item['title'],
                    style: TextStyle(
                      color: Utils.hexToColor('#333333'),
                      fontSize: 16,
                      // letterSpacing: 6.w
                    ),
                  ),
                ),
                Container(
                  width: 525.w,
                  height: 56.h,
                  child: TextField(
                    obscureText: true,
                    controller: item['controller'],
                    style:
                        TextStyle(fontSize: 14, color: Colors.black), //输入文本的样式
                    decoration: InputDecoration(
                      hintText: item['tips'],
                      hintStyle:
                          TextStyle(color: Color(0xFFC8C8D9), fontSize: 16),
                      contentPadding: EdgeInsets.fromLTRB(0.w, 0, 21.w, 0),
                      fillColor: Colors.white,
                      filled: true,
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(4.w),
                        ),
                        borderSide: BorderSide(
                          color: Colors.white,
                          width: 0,
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.white,
                          width: 1,
                        ),
                        borderRadius: BorderRadius.all(
                          Radius.circular(4.w),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Offstage(
            offstage: index == 3 ? true : false,
            child: Container(
              width: double.infinity,
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(color: Utils.hexToColor('#F7F7F7')))),
            ),
          )
        ],
      ));
    }

    return Column(
      children: widget,
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return DefaultTabController(
        length: 3,
        initialIndex: 0,
        child: Scaffold(
            appBar: TopBar(
              title: '修改密码',
              backgroundColor: Utils.hexToColor('#297CFF'),
            ),
            body: Container(
                color: Utils.hexToColor('#F5F6FA'),
                child: Column(children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 30.w),
                    child: Column(children: <Widget>[
                      Container(
                          height: 362.w,
                          color: Colors.white,
                          padding: EdgeInsets.fromLTRB(25.w, 0, 25.w, 0),
                          child: _buildInputBox()),
                    ]),
                  ),
                  Container(
                      width: 700.w,
                      height: 100.w,
                      margin: EdgeInsets.only(top: 40.w),
                      child: ElevatedButton(
                          onPressed: () {
                            updatePassword();
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Utils.hexToColor('#297CFF'),
                            shape: RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(8.w))),
                          ),
                          child: Text('保存',
                              style: TextStyle(
                                  color: Colors.white, fontSize: 16))))
                ]))));
  }
}
